from tqdm import tqdm
import requests
from bs4 import BeautifulSoup

from Function.Database import read_column_data_to_list
from Data import GlobalValue

def two_dimension_schedule_display(weeks, schedule_chart):
    # 是否成功获取数据
    if schedule_chart:
        # 成功获取数据，输出二维图像课表
        print(f"第{weeks}周课表：")
        print(" 一  二  三  四  五  六  七")
        for lesson in schedule_chart:
            for day in lesson:
                # day为-1表示间歇，不输出
                if day != -1:
                    print("{: ^3d}".format(day), end="\t")
            print("")
    else:
        print("数据未成功获取，请检查网络。")
    print("")


def schedule_chart_info(id_num: str, week_num: int) -> list:
    # 课表查询网站
    base_url = "http://jwzx.cqupt.edu.cn/kebiao/kb_stu.php?xh="
    # 二维图形课表的列表形式
    schedule_chart = [
        # 周1、2、3、4、5、6、7
        [0, 0, 0, 0, 0, 0, 0],  # 第1、2节
        [0, 0, 0, 0, 0, 0, 0],  # 第3、4节
        [-1, -1, -1, -1, -1, -1, -1],  # 中午间歇节
        [0, 0, 0, 0, 0, 0, 0],  # 第5、6节
        [0, 0, 0, 0, 0, 0, 0],  # 第7、8节
        [-1, -1, -1, -1, -1, -1, -1],  # 下午间歇
        [0, 0, 0, 0, 0, 0, 0],  # 第9、10节
        [0, 0, 0, 0, 0, 0, 0],  # 第11、12节
    ]

    # 头部信息
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 Edg/122.0.0.0",
    }

    # 使用requests库发送GET请求
    response = requests.get(base_url + id_num, headers=headers)

    # 检查请求是否成功
    if response.status_code == 200:
        # 使用BeautifulSoup解析HTML内容
        soup = BeautifulSoup(response.content, "html.parser")

        # 查找含有特定class的table标签
        table_tags = soup.find_all('table')
        # 遍历table标签
        for table in table_tags:
            lesson = 0
            # 在table标签里面找tr标签
            tr_tags = table.find_all('tr')
            # 遍历所有找到的tr标签
            for tr in tr_tags:
                day = 0
                lesson += 1
                # 在tr标签中找所有td标签
                td_tags = tr.find_all("td")
                # 遍历所有td标签
                for td in td_tags:
                    day += 1
                    # 在所有td标签中找到所有div标签
                    div_tags = td.find_all("div", class_='kbTd')
                    # 打印所有div标签的内容
                    for div in div_tags:
                        week = 0
                        weekList = []
                        # 获取div标签的zc属性
                        zc_attribute = div.get('zc')
                        # 将zc属性转换为列表，并遍历
                        for item in list(zc_attribute):
                            week += 1
                            # 判断要查询的周数是否为0
                            if week_num != 0:
                                # 如果要查询的周数不为0，则只显示weekNum那一周的课表
                                if item != "0" and week == week_num:
                                    weekList.append(str(week))
                            elif week_num == 0:
                                # 如果要查询的周数为0，则显示所有周的课表
                                if item != "0":
                                    weekList.append(str(week))

                        # 在div标签中找font标签，确定一次课是几节课连上
                        font_tags = div.find_all("font")
                        # 遍历所有font标签，并获取font标签中的文本
                        for font in font_tags:
                            # 如果文本为空，则2节连上，如果文本第一个字符为“4”，则四节连上
                            lessons_num = font.get_text()

                        # 课程不为空，则输出
                        if len(weekList) != 0:
                            try:
                                # font标签中获得的字符串为“4节连上”
                                lessons_num[0] == "4"
                                schedule_chart[lesson - 2][day - 2] = 1
                                schedule_chart[lesson - 1][day - 2] = 1
                            except IndexError:
                                # font标签中获得的字符串为空，说明2节连上
                                schedule_chart[lesson - 2][day - 2] = 1
        # 返回二维列表信息
        return schedule_chart
    else:
        print('Failed to retrieve the webpage.')
        print(f"StateCode:{response.status_code}")


def students_schedule(id_num, week_num, table_name=None):
    if table_name is not None:  # 查询集体

        # 获取相关信息
        students_id = read_column_data_to_list(GlobalValue.database_address, table_name, "ID")

        # 二维图形课表
        schedule_chart = [
            # 周1、2、3、4、5、6、7
            [0, 0, 0, 0, 0, 0, 0],  # 第1、2节
            [0, 0, 0, 0, 0, 0, 0],  # 第3、4节
            [-1, -1, -1, -1, -1, -1, -1],  # 中午间歇节
            [0, 0, 0, 0, 0, 0, 0],  # 第5、6节
            [0, 0, 0, 0, 0, 0, 0],  # 第7、8节
            [-1, -1, -1, -1, -1, -1, -1],  # 下午间歇
            [0, 0, 0, 0, 0, 0, 0],  # 第9、10节
            [0, 0, 0, 0, 0, 0, 0],  # 第11、12节
        ]
        schedule_dict = {}

        if week_num == 0:
            print("不支持查看所有学生所有周的课表")
        else:
            # 获取课表的简略图列表信息，并显示进度条
            for student_id in tqdm(students_id, desc="获取数据中：", unit="人"):
                schedule_dict[student_id] = schedule_chart_info(student_id, week_num)
            print("数据获取完成")

            # 循环计数
            for student_id, student_schedule in schedule_dict.items():
                lesson_num = 0
                for lesson in student_schedule:
                    lesson_num += 1
                    day_num = 0
                    for day in lesson:
                        day_num += 1
                        if day == 1:
                            schedule_chart[lesson_num - 1][day_num - 1] += 1
                            if lesson_num == 1 and day_num == 5:
                                print(student_id)
            # 输出显示二维课表
            two_dimension_schedule_display(week_num, schedule_chart)
    else:  # 查询个人
        if week_num == 0:
            schedule_chart_info_list = []
            # 获取课表的简略图列表信息，并显示进度条
            for week_num in tqdm(range(1, 20), desc="获取数据中：", unit="周"):
                # 获取课表的简略图表信息
                schedule_chart_info_list.append(schedule_chart_info(id_num, week_num))
            print("数据获取完成")
            for schedule_chart, week_num in zip(schedule_chart_info_list, range(1, 20)):
                print(f"当前查询学号：{id_num}")
                two_dimension_schedule_display(week_num, schedule_chart)
        else:
            print(f"当前查询学号：{id_num}，查询周数：{week_num}")
            # 获取二维课表
            schedule_chart = schedule_chart_info(id_num, week_num)
            # 输出二维课表
            two_dimension_schedule_display(week_num, schedule_chart)


def menu():
    while True:
        # 获取相关信息
        print("多个学号以空格分隔\n"
              "1：查询学号2021210584\n"
              "2：查询班级的所以学生\n"
              "3：查询光信息专业所有学生\n"
              "0：退出")

        id_num_str = input("请输入要查询的学号：")
        if id_num_str == "0":
            break
        week_num_str = input("请输入要查询的周数（输入0查询所有周的课表）（多个数字以空格分隔）：")
        id_num_list = id_num_str.split(" ")
        week_num_list = week_num_str.split(" ")

        for id_num in id_num_list:
            for week_num in week_num_list:
                match id_num:
                    case "1":
                        students_schedule("2021210584", int(week_num))
                    case "2":
                        students_schedule(id_num, int(week_num), "students")
                    case "3":
                        students_schedule(id_num, int(week_num), "optical_information")
                    case _:
                        students_schedule(id_num, int(week_num))
